//
//  JSTPickerView.m
//  KYKJPackDemo
//
//  Created by 01 on 17/6/20.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTPickerView.h"
#define kheadViewHeight     44*kWidthProportion
#define kpickerViewHeight   160*kWidthProportion
#define kfootViewHeight     44*kWidthProportion
#define kcontentViewHeight   (kheadViewHeight + kpickerViewHeight + kfootViewHeight)

@interface JSTPickerView ()
{
    NSInteger selectedYearRow;
    NSInteger selectedMonthRow;
}
@property (nonatomic, strong) UIView            *bgView;
@property (nonatomic, strong) UIView            *contentView;
@property (nonatomic, strong) UIView            *headView;
@property (nonatomic, strong) UILabel           *headTitleLbl;
@property (nonatomic, strong) UIPickerView      *pickerView;
@property (nonatomic, strong) UIView            *footView;
@property (nonatomic, assign) PickerViewType    pickerViewType;             //展示类型

@property (nonatomic, strong) NSMutableArray           *firstComponentArr;         //第一列数据
@property (nonatomic, strong) NSMutableArray           *secondComponentArr;        //第二列数据
@property (nonatomic, strong) NSMutableArray           *thirdComponentArr;         //第三列数据
@property (nonatomic, strong) NSMutableArray           *fourComponentArr;          //第四列数据
@property (nonatomic, strong) NSMutableArray           *allComponentArr;           //列的总数

@end

@implementation JSTPickerView

- (id)initWithFrame:(CGRect)frame items:(NSArray *)items getType:(PickerViewType)type
{
    if (self = [super initWithFrame:frame])
    {
        _logisticsArr = [[NSMutableArray alloc] initWithArray:items];
        self.backgroundColor = [UIColor clearColor];
        self.pickerViewType = type;
        [self addSubview:self.contentView];
        [self.contentView addSubview:self.headView];
        [self.contentView addSubview:self.pickerView];
        [self.contentView addSubview:self.footView];
        
        [self setPickerViewDataSourceWithType:type string:nil];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame string:(NSString *)string getType:(PickerViewType)type
{
    if (self = [super initWithFrame:frame])
    {
        self.backgroundColor = [UIColor clearColor];
        self.pickerViewType = type;
        [self addSubview:self.contentView];
        [self.contentView addSubview:self.headView];
        [self.contentView addSubview:self.pickerView];
        [self.contentView addSubview:self.footView];
        
        [self setPickerViewDataSourceWithType:type string:string];
    }
    return self;
}

- (NSMutableArray *)allComponentArr
{
    if (!_allComponentArr) {
        _allComponentArr = [[NSMutableArray alloc]init];
    }
    return _allComponentArr;
}

- (NSMutableArray *)firstComponentArr
{
    if (!_firstComponentArr) {
        _firstComponentArr = [[NSMutableArray alloc]init];
    }
    return _firstComponentArr;
}

- (NSMutableArray *)secondComponentArr
{
    if (!_secondComponentArr) {
        _secondComponentArr = [[NSMutableArray alloc]init];
    }
    return _secondComponentArr;
}

- (NSMutableArray *)thirdComponentArr
{
    if (!_thirdComponentArr) {
        _thirdComponentArr = [[NSMutableArray alloc]init];
    }
    return _thirdComponentArr;
}

- (NSMutableArray *)fourComponentArr
{
    if (!_fourComponentArr) {
        _fourComponentArr = [[NSMutableArray alloc]init];
    }
    return _fourComponentArr;
}

- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
        _contentView.frame = CGRectMake(kWidthProportion*40, (kDeviceHeight -kheadViewHeight-kpickerViewHeight-kfootViewHeight)/2, self.width  - kWidthProportion*40*2, kcontentViewHeight);
        _contentView.userInteractionEnabled = YES;
        _contentView.backgroundColor = [UIColor clearColor];
        [_contentView.layer setCornerRadius:8];
        _contentView.layer.masksToBounds = YES;
    }
    return _contentView;
}

-(UIView *)headView
{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.width - kWidthProportion*40*2, kheadViewHeight)];
        _headView.backgroundColor = kANGNavColor;
        [_headView addSubview:self.headTitleLbl];
        
    }
    return _headView;
}

- (UILabel *)headTitleLbl
{
    if (!_headTitleLbl) {
        _headTitleLbl = [[UILabel alloc]init];
        _headTitleLbl.frame = CGRectMake(0, 0, _headView.width, _headView.height);
        _headTitleLbl.font = [UIFont boldSystemFontOfSize:16];
        _headTitleLbl.textAlignment = NSTextAlignmentCenter;
        _headTitleLbl.text = @"请 选 择";
        _headTitleLbl.textColor = kWhiteColor;
        _headTitleLbl.backgroundColor = [UIColor clearColor];
        
    }
    return _headTitleLbl;
}

-(UIPickerView *)pickerView
{
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc]init];
        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.delegate=self;
        _pickerView.dataSource=self;
        _pickerView.userInteractionEnabled = YES;
        _pickerView.frame=CGRectMake(_headView.frame.origin.x, _headView.bottom, _headView.width, kpickerViewHeight);
    }
    return _pickerView;
}

-(UIView *)footView
{
    if (!_footView) {
        _footView = [[UIView alloc]initWithFrame:CGRectMake(_headView.frame.origin.x, _pickerView.bottom, _headView.width, kfootViewHeight)];
        _footView.backgroundColor = [UIColor clearColor];
        
        UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, _footView.width/2, kfootViewHeight)];
        [cancelBtn setBackgroundImage:[UIImage streImageNamed:@"SNAlertButton_left"] forState:UIControlStateNormal];
        [cancelBtn setBackgroundImage:[UIImage streImageNamed:@"SNAlertButton_left"] forState:UIControlStateHighlighted];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:kANGBrownColor forState:UIControlStateNormal];
        [cancelBtn addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];
        cancelBtn.titleLabel.font = [UIFont fontWithName:HelBold size:16.0f];
        
        UIButton *confirmBtn = [[UIButton alloc]initWithFrame:CGRectMake(cancelBtn.right, cancelBtn.frame.origin.y, _footView.width/2, kfootViewHeight)];
        [confirmBtn setBackgroundImage:[UIImage streImageNamed:@"SNAlertButton_right"] forState:UIControlStateNormal];
        [confirmBtn setBackgroundImage:[UIImage streImageNamed:@"SNAlertButton_right"] forState:UIControlStateHighlighted];
        [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
        [confirmBtn setTitleColor:kANGNavColor forState:UIControlStateNormal];
        [confirmBtn addTarget:self action:@selector(confirmActionPressed) forControlEvents:UIControlEventTouchUpInside];
        confirmBtn.titleLabel.font = [UIFont fontWithName:HelBold size:16.0f];
        
        [_footView addSubview:cancelBtn];
        [_footView addSubview:confirmBtn];
        
    }
    return _footView;
}

- (void)showOnWindow
{
    UIWindow *window = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).window;
    
    [window addSubview:self];
    
    _bgView= [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight)];
    _bgView.backgroundColor = [UIColor blackColor];
    _bgView.alpha = 0.5;
    [window insertSubview:_bgView belowSubview:self];
}

- (void)dismissView
{
    [_bgView removeFromSuperview];
    [self removeFromSuperview];
}

- (void)confirmActionPressed
{
    NSString *resultStr = @"";
    
    for (int i = 0; i < self.allComponentArr.count; i ++)
    {
        NSInteger selectedRow = [self.pickerView selectedRowInComponent:i];
        NSArray *arr = [self.allComponentArr safeObjectAtIndex:i];
        
        NSString *str = @"";
        
        if (self.pickerViewType == birthdayType)
        {
//            if (i == 2)
//            {
//                NSRange range = NSMakeRange(0, 2);
//                NSString *str1  = [NSString stringWithFormat:@"%@",[arr safeObjectAtIndex:selectedRow]];
//                str = [str1 substringWithRange:range];
//            }
//            else if (i == 3)
//            {
//                NSRange range = NSMakeRange(0, 3);
//                NSString *str2 = [NSString stringWithFormat:@"%@",[arr safeObjectAtIndex:selectedRow]];
//                str = [str2 substringWithRange:range];
//            }
//            else
//            {
//                str  = [NSString stringWithFormat:@"%@",[arr safeObjectAtIndex:selectedRow]];
//            }
            str  = [NSString stringWithFormat:@"%@",[arr safeObjectAtIndex:selectedRow]];
        }
        else
        {
            if (i == 0)
            {
                str = [NSString stringWithFormat:@"%@",[arr safeObjectAtIndex:selectedRow]];
                if ([str isEqualToString:@"0"])
                {
                    str = @"";
                }
            }
            else
            {
                str = [NSString stringWithFormat:@"%@",[arr safeObjectAtIndex:selectedRow]];
            }
        }
        resultStr = [resultStr stringByAppendingString:str];
    }
    if ([self.delegate respondsToSelector:@selector(confirmBtnHaveClick:resultString: indexPath:)])
    {
        [self.delegate confirmBtnHaveClick:self resultString:resultStr indexPath:self.indexPath];
    }
}

#pragma mark piackView 数据源方法
// pickerView 列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return self.allComponentArr.count;
}

// pickerView 每列个数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (self.pickerViewType == birthdayType)
    {
        if (component ==0)
        {
            return self.firstComponentArr.count;
        }else if (component == 1)
        {
            return 12;
        }
        else
        {
            if (selectedMonthRow == 0 || selectedMonthRow == 2 ||
                selectedMonthRow == 4 || selectedMonthRow == 6 ||
                selectedMonthRow == 7 || selectedMonthRow == 9 ||
                selectedMonthRow == 11) {
                return 31;
            }
            else if (selectedMonthRow == 1)
            {
                NSInteger yearint = [_currentYearString integerValue];
                if (((yearint % 4 == 0)&&(yearint % 100 != 0)) ||
                    (yearint % 400 == 0)) {
                    return 29;
                }
                else
                {
                    return 28;
                }
            }
            else
            {
                return 30;
            }
        }
    }else
    {
        return 2;
    }
    
    return 0;
}

#pragma mark UIPickerViewdelegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel * titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, kDeviceWidth, 25)];
    titleLbl.backgroundColor = [UIColor clearColor];
    titleLbl.font =  [UIFont systemFontOfSize:15];
    titleLbl.textColor = kANGBrownColor;
    titleLbl.textAlignment = NSTextAlignmentCenter;
    
    if (component ==0)
    {
        titleLbl.text = [self.firstComponentArr safeObjectAtIndex:row];
    }
    else if (component == 1)
    {
        titleLbl.text = [self.secondComponentArr safeObjectAtIndex:row ];
    }
    else if (component == 2)
    {
        titleLbl.text = [self.thirdComponentArr safeObjectAtIndex:row];
    }
    else if (component == 3)
    {
        titleLbl.text = [self.fourComponentArr safeObjectAtIndex:row];
    }
    
    return titleLbl;
    
}

//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    if (component == 0)
    {
        return [self.firstComponentArr safeObjectAtIndex:row];
    }
    else if (component == 1)
    {
        return [self.secondComponentArr safeObjectAtIndex:row];
    }
    else
    {
        return [self.thirdComponentArr safeObjectAtIndex:row];
    }
    return nil;
}

// 每列宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (self.pickerViewType == birthdayType)
    {
        return 50*kWidthProportion;
    }
    return 100;
}

// 返回选中的行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 1)
    {
        selectedMonthRow = row;
        [pickerView reloadAllComponents];
    }
    
    NSString *resultStr = @"";
    for (int i = 0; i < self.allComponentArr.count; i ++)
    {
        NSInteger selectedRow = [self.pickerView selectedRowInComponent:i];
        NSArray *arr = [self.allComponentArr safeObjectAtIndex:i];
        
        NSString *str = @"";
        if (i == 2)
        {
            str = [NSString stringWithFormat:@" %@",[arr safeObjectAtIndex:selectedRow]];
        }
        else if (i == 3)
        {
            str = [NSString stringWithFormat:@" %@",[arr safeObjectAtIndex:selectedRow]];
        }
        else
        {
            str  = [NSString stringWithFormat:@"%@",[arr safeObjectAtIndex:selectedRow]];
        }
        resultStr = [resultStr stringByAppendingString:str];
        self.headTitleLbl.text = [NSString stringWithFormat:@"%@",resultStr];
        
    }
}

- (void) setPickerViewDataSourceWithType:(PickerViewType)type string:(NSString *)string
{
    switch (type) {
            case sexType:
        {
            self.firstComponentArr = [NSMutableArray arrayWithObjects:@"男",@"女",nil];
            self.allComponentArr = [NSMutableArray arrayWithObjects:self.firstComponentArr,nil];
            if (string)
            {
                [self.pickerView selectRow:[self.firstComponentArr indexOfObject:string] inComponent:0 animated:YES];
            }
            else
            {
                [self.pickerView selectRow:0 inComponent:0 animated:YES];
            }
        }
            break;
            case birthdayType:
        {
            NSDate *date = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy"];
            _currentYearString = [NSString stringWithFormat:@"%@年",[formatter stringFromDate:date]];
            
            [formatter setDateFormat:@"MM"];
            _currentMonthString = [NSString stringWithFormat:@"%ld月",(long)[[formatter stringFromDate:date]integerValue]];
            
            [formatter setDateFormat:@"dd"];
            _currentDayString = [NSString stringWithFormat:@"%@日",[formatter stringFromDate:date]];
            
            NSInteger currentYear = [_currentYearString integerValue];
            
            for (NSInteger i = 1900; i <=currentYear; i++) {
                
                NSString *str = [NSString stringWithFormat:@"%ld年",(long)i];
                [self.firstComponentArr addObject:str];
            }
            for (NSInteger i = 1; i <= 12; i++) {
                
                NSString *str = [NSString stringWithFormat:@"%ld月",(long)i];
                [self.secondComponentArr addObject:str];
            }
            for (NSInteger i = 1; i <=31; i++) {
                
                NSString *str = [NSString stringWithFormat:@"%02ld日",(long)i];
                [self.thirdComponentArr addObject:str];
            }
            self.allComponentArr = [NSMutableArray arrayWithObjects:self.firstComponentArr,self.secondComponentArr,self.thirdComponentArr,nil];
            
            selectedMonthRow = [self.firstComponentArr indexOfObject:_currentMonthString];
            [self.pickerView selectRow:[self.firstComponentArr indexOfObject:_currentYearString] inComponent:0 animated:YES];
            [self.pickerView selectRow:[self.secondComponentArr indexOfObject:_currentMonthString] inComponent:1 animated:YES];
            [self.pickerView selectRow:[self.thirdComponentArr indexOfObject:_currentDayString] inComponent:2 animated:YES];
            
            
            self.headTitleLbl.text = [NSString stringWithFormat:@"%@ %@ %@", _currentYearString, _currentMonthString, _currentDayString];
        }
            break;
            
        default:
            break;
    }
}
@end
